package common

import (
	"gitee.com/song-yao-shun/MQH/model"
	"github.com/dgrijalva/jwt-go"
	"time"
)

//定义加密的秘钥
var jwtKey = []byte("songys_mqj_qa_help_center")
//定义token的Claims
type Claims struct {
	UserId uint
	UserName string
	jwt.StandardClaims
}

//token的生成方法
func ReleaseToken(user model.User)(string, error){
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	//设置Claims
	claims := &Claims{
		UserId: 		user.ID,
		UserName: 		user.Name,
		StandardClaims:	jwt.StandardClaims{
			//设置token的过期时间
			ExpiresAt: 	expirationTime.Unix(),
			//token发放时间
			IssuedAt: 	time.Now().Unix(),
			//token发放人
			Issuer: 	"mqj.songys",
			//主题
			Subject: 	"user token",
		},
	}
	//生成
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil{
		return "", err
	}
	return tokenString,  err
}

func ParseToken(tokenString string)(*jwt.Token, *Claims, error){
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	return token, claims, err
}